#!/usr/bin/env python
# -*- coding: utf-8 -*-

from farado.items.message import Message
from farado.items.field_kind import ValueTypes
from farado.general_manager_holder import gm_holder



class ChangesUserNotifier():
    def __init__(self, user_id) -> None:
        self.user_id = user_id

    def notify_by_issue(self, issue, change):
        if not issue or not change:
            return

        # TODO : перенести удаление старых сообщений в отдельную логику
        gm_holder.meta_item_manager.raw_querier.remove_old_messages()

        issue_kind = gm_holder.project_manager.issue_kind(issue.issue_kind_id)
        workflow = gm_holder.project_manager.workflow(issue_kind.workflow_id)

        caption  = f'Изменения: '
        caption += f'«{workflow.caption}: {issue_kind.caption} #{issue.id}: '
        caption += f'{issue.caption}»'

        content  = f'В запросе «[{issue.caption}](/issues/issue/{issue.id})» '
        content += f'выполнены изменения:'

        for receiver_id in self.users_from_issue(issue):
            if receiver_id == self.user_id:
                continue
            gm_holder.project_manager.save_item(
                Message(
                    caption=caption,
                    content=content,
                    receiver_id=receiver_id,
                    sender_id=self.user_id,
                    issue_change_id=change.id,
                )
            )

    def users_from_issue(self, issue):
        users_ids = set()

        for change in issue.changes:
            users_ids.add(int(change.user_id))

        for comment in issue.comments:
            users_ids.add(int(comment.user_id))

        for field in issue.fields:
            field_kind = gm_holder.project_manager.field_kind(field.field_kind_id)
            if not field_kind:
                continue
            if ValueTypes.user_id == field_kind.value_type:
                if user_id := int(field.value):
                    users_ids.add(user_id)
            elif ValueTypes.users_ids == field_kind.value_type:
                for value in str(field.value).split(','):
                    if user_id := int(value):
                        users_ids.add(user_id)
        return users_ids
